const http = require('http')
const fs = require('fs')
const socketIo = require('socket.io')

const run = function ({ app, config }) {
  const httpServer = http.Server(app)
  const io = socketIo(httpServer , {
    maxHttpBufferSize: 1e9,
    pingTimeout: 60000,
    httpCompression: {
      // Engine.IO options
      threshold: 2048, // defaults to 1024
      // Node.js zlib options
      chunkSize: 8 * 1024, // defaults to 16 * 1024
      windowBits: 14, // defaults to 15
      memLevel: 7, // defaults to 8
    }
  })
  const users = {}
  io.on('connection' , (socket) => {
    socket.on('login' , (nickname) => {
      if (users[nickname]) {
        socket.emit('repeat' , '昵称重复')
        return 
      }
      socket.nickname = nickname
      users[nickname] = {
        name: nickname,
        socket : socket,
      }
      io.sockets.emit('logged' , {nickname , isLogin: true, wsid: socket.id} )
      console.log((nickname ? nickname + ':' : '') + '连接成功')
    })
    socket.on('disconnecting', (reason) => {
      let nickname = socket?.nickname
      if (nickname && users[nickname]) {
        delete users[nickname]
        io.sockets.emit('logout' , {nickname , isLogin: false} )
        delete socket[nickname]
      }
      console.log((nickname ? nickname + ':' : '') + '断开连接')
    })
    socket.on('chat' , ({ msg, type, fid, code }) => {
      socket.broadcast.emit('response_chat' , {
        nickname: socket.nickname,
        msg: msg,
        type: type,
        fid: fid,
        code: code,
        time: Date.now()
      })
    })
    // 客户端请求下载文件
    socket.on('file_request_download' , ({ msg, type, fid }) => {
      // 向客户端广播拉取文件请求
      io.sockets.emit('file_pull_from_client' , {
        filename: msg,
        type: type,
        fid: fid,
        wsid: socket.id,
        time: Date.now()
      })
    })
    // 接收客户端传入的文件
    socket.on('file_push_to_server', (stream, data) => {
      let ws = io.sockets.sockets.get(data.wsid)
      if (ws) {
        console.log('推送文件至客户端')
        ws.emit('file_push_to_client' , stream, data)
      }
    })
  })

  httpServer.listen(config.constant.socketPort)
  console.log('Socket Server is running on: ws://localhost:' + config.constant.socketPort)
}

module.exports = {
  run
}
